#include "log.h"


Log::Log(QObject *parent) : QObject(parent)
{

}

void Log::RecordLog()
{
    DelTimeOutLog();
    qInstallMessageHandler(SaveLog);
}

QString getLogPath()
{
    QString path = QCoreApplication::applicationDirPath()+"/log/";
    if(!QDir(path).exists()){ //创建目录
        QDir().mkdir(path);
    }
    return path;
}

void Log::DelTimeOutLog()
{
    QString date_str = QDateTime::currentDateTime().toString("yyyyMMdd");
    int abort_date = date_str.toInt() - MAX_STORE_DAYS; // 计算过期日期

    QString dir = getLogPath();
    QDir log_dir(dir);
    log_dir.setFilter(QDir::NoDotAndDotDot | QDir::Files);  // 只遍历文件
    QFileInfoList file_list = log_dir.entryInfoList();

    for (const QFileInfo &file_info : file_list) {
        QString file_name = file_info.fileName();

        // 匹配文件名是否符合 "yyyy-MM-dd_hh-mm-ss.log" 格式，例如 "2024-03-06_14-25-30.log"
        QRegularExpression regex(R"(^(\d{4})-(\d{2})-(\d{2})_.*\.log$)");  // 新的正则表达式
        QRegularExpressionMatch match = regex.match(file_name);

        if (match.hasMatch()) {
            int file_date = QString(match.captured(1) + match.captured(2) + match.captured(3)).toInt(); // 拼接成 yyyyMMdd

            if (file_date < abort_date) {
                QFile delete_file(file_info.absoluteFilePath());
                if (delete_file.remove()) {
                    qDebug() << "删除过期日志: " << file_info.absoluteFilePath();
                } else {
                    qWarning() << "删除失败: " << file_info.absoluteFilePath();
                }
            }
        }
    }

}


void Log::SaveLog(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
    static QMutex m;
    m.lock();

    static QString log_dir = getLogPath();
    static QString log_name= log_dir + QDateTime::currentDateTime().toString("yyyy-MM-dd hh-mm-ss.log");
    static QFile file(log_name);

    //2、文件大小判断
    if(file.size() >= MAX_FILE_SIZE)//如果日志文件超过100M,则另写一个
    {
        file.rename(log_name,log_dir+QDateTime::currentDateTime().toString("yyyy-MM-dd hh-mm-ss.log"));
        file.setFileName(log_name);
    }

    //3、写入文件
    QString level;
    switch (type) {
        case QtDebugMsg: level = "[DEBUG]"; break;
        case QtInfoMsg: level = "[INFO]"; break;
        case QtWarningMsg: level = "[WARNING]"; break;
        case QtCriticalMsg: level = "[ERROR]"; break;
    }

    QString message="[" + QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz") + "]" + level + " "+msg;
    std::cout<<message.toLocal8Bit().constData()<<std::endl; //安装了日志以后qDebug就不再打印了，需要借助C++的打印

    if(!file.open(QIODevice::WriteOnly | QIODevice::Append)){

        std::cout<<file.errorString().toLocal8Bit().constData()<<std::endl;
        return;
    }

    QTextStream stream(&file);
    stream << message<< "\r\n";
    file.flush();
    file.close();

    m.unlock();
}

